//
//  Compose.swift
//  MicroBlog
//
//  Created by 002 on 15/10/26.
//  Copyright © 2015年 002. All rights reserved.
//

import UIKit
import SVProgressHUD

class ComposeViewController: UIViewController {

    // MARK: - 监听方法
    /// 关闭
    @objc private func close() {
        
        // 1. 关闭键盘
        textView.resignFirstResponder()
        // 2. 退出当前控制器
        dismissViewControllerAnimated(true, completion: nil)
    }
    
    /// 发布微博
    @objc private func sendStatus() {
        
        // 1. 获取文本内容
        let text = textView.emoticonText
        
        // 2. 发布微博
        let image = picturePickerController.pictures.last
        NetworkTools.sharedTools.sendStatus(text, image: image) { (result, error) -> () in
            
            if error != nil {
                print("出错了")
                SVProgressHUD.showInfoWithStatus("您的网络不给力")
                return
            }
            print("\(result)")
            // 关闭控制器
            self.close()
        }
    }
    
    /// 选择表情
    @objc private func selectEmoticon() {
        
        // 1. 退出键盘
        textView.resignFirstResponder()
        
        // 2. 替换视图
        textView.inputView = (textView.inputView == nil ? emoticonView : nil)
        
        // 3. 重新激活键盘
        textView.becomeFirstResponder()
    }
    
    /// 旋转图片
    @objc private func selectPicture() {
        
        // 1. 退出键盘
        textView.resignFirstResponder()
        
        // 2. 判断还需要更新约束
        if picturePickerController.view.bounds.height > 0 {
            return
        }
        
        // 3. 更新照片选择器约束
        picturePickerController.view.snp_updateConstraints { (make) -> Void in
            make.height.equalTo(view.bounds.height * 0.6)
        }
        
        // 4. 修改textView约束 - 重建约束 - 会将之前`textView`的所有的约束删除
            textView.snp_remakeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(picturePickerController.view.snp_top)
        }
        
        // 5. 动画更新约束
        UIView.animateWithDuration(0.5) { () -> Void in
            self.view.layoutIfNeeded()
        }
    }
    
    // MARK: - 键盘处理
    /// 键盘变化处理
    @objc private func keyboardChanged(notification: NSNotification) {
        print(notification)
        
        // 1. 获取目标的 rect - 字典中的`结构体`是 NSValue
        let rect = (notification.userInfo![UIKeyboardFrameEndUserInfoKey] as! NSValue).CGRectValue()
        // 获取目标的动画时长 - 字典中的数值是 NSNumber
        let duration = (notification.userInfo![UIKeyboardAnimationDurationUserInfoKey] as! NSNumber).doubleValue
        // 动画曲线数值
        let curve = (notification.userInfo![UIKeyboardAnimationCurveUserInfoKey] as! NSNumber).integerValue
        
        let offset = -UIScreen.mainScreen().bounds.height + rect.origin.y
        
        // 2. 更新约束
        toolbar.snp_updateConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom).offset(offset)
        }
        
        // 3. 动画 － UIView 块动画 本质上是对 CAAnimation 的包装
        UIView.animateWithDuration(duration) { () -> Void in
            // 设置动画曲线
            /**
            曲线值 = 7
            － 如果之前的动画没有完成，有启动了其他的动画，让动画的图层直接运动到后续动画的目标位置
            － 一旦设置了 `7`，动画时长无效，动画时长统一变成 0.5s 上面的 duration 无效
            */
            UIView.setAnimationCurve(UIViewAnimationCurve(rawValue: curve)!)
            
            self.view.layoutIfNeeded()
        }
        
        // 调试动画时长 － keyPath 将动画添加到图层
        let anim = toolbar.layer.animationForKey("position")
        print("动画时长 \(anim?.duration)")
    }
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // 添加键盘通知
        NSNotificationCenter.defaultCenter().addObserver(self, selector: "keyboardChanged:", name: UIKeyboardWillChangeFrameNotification, object: nil)
    }
    
    deinit {
        // 注销通知
        NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    
    // MARK: - 视图生命周期
    override func loadView() {
        super.loadView()
//        view = UIView()
        setupUI()
    }

    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        // 判断是否需要打开键盘
        if picturePickerController.view.bounds.height == 0 {
            textView.becomeFirstResponder()
        }
    }
    
    // MARK: 懒加载控件
    /// 照片选择器
    private lazy var picturePickerController : PicturePickerController = PicturePickerController()
    
    /// 表情键盘视图
    private lazy var emoticonView : EmoticonView = EmoticonView { [weak self] (emoticon) -> () in
        
        self?.textView.insertEmoticon(emoticon)
    }
    
    /// 工具条
    private lazy var toolbar : UIToolbar = UIToolbar()
    
    /// 文本视图
    private lazy var textView : UITextView = {
        
        // 创建textView
        let tv = UITextView()
        
        // 设置属性
        tv.font = UIFont.systemFontOfSize(18)
        tv.textColor = UIColor.darkGrayColor()
        
        // 始终运行垂直滚动
        tv.alwaysBounceVertical = true
        
        // 拖拽关闭键盘
        tv.keyboardDismissMode = UIScrollViewKeyboardDismissMode.OnDrag
        
        // 设置文本视图代理
        tv.delegate = self
        
        return tv
    }()
    
    /// 站位标签
    private lazy var placeHolderLabel : UILabel = UILabel.init(title: "分享新鲜事...", fontSize: 18, color: UIColor.lightGrayColor())
    
}


// MARK: - UITextViewDelegate
extension ComposeViewController : UITextViewDelegate {
    
    func textViewDidChange(textView: UITextView) {
        navigationItem.rightBarButtonItem?.enabled = textView.hasText()
        placeHolderLabel.hidden = textView.hasText()
    }
}

// MARK: - 设置界面
private extension ComposeViewController {
    
    func setupUI() {
    
        // 0. 取消滚动视图间距
        automaticallyAdjustsScrollViewInsets = false
        
        // 1. 设置背景颜色
        view.backgroundColor = UIColor.whiteColor()
        
        // 2. 设置控件
        prepareForNavigationBar()
        prepareForToolbar()
        prepareForTextView()
        prepareForPicturePicker()
    }
    
    // MARK: - 准备照片选择器
    private func prepareForPicturePicker() {
        
        // 1. 添加子控制器 - 为了保证响应者链条能够正常传递
        addChildViewController(picturePickerController)
        
        // 2. 添加view
        view.insertSubview(picturePickerController.view, belowSubview: toolbar)
        
        // 3. 布局
        picturePickerController.view.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            // 因为进入界面的时候还不需要显示，所以高度先设置0，然后点击选择图片的时候还需要修改textView的约束，到时再添加约束
            make.height.equalTo(0)
        }
    }
    
    // MARK: 设置导航栏
    private func prepareForNavigationBar() {
        
        // 1. 左右按钮
        navigationItem.leftBarButtonItem = UIBarButtonItem.init(title: "取消", style: .Plain, target: self, action: "close")
        navigationItem.rightBarButtonItem = UIBarButtonItem.init(title: "发布", style: .Plain, target: self, action: "sendStatus")
        
        // 禁用发布按钮
        navigationItem.rightBarButtonItem?.enabled = false
        
        // 2. 标题视图
        let titleView = UIView.init(frame: CGRectMake(0, 0, 200, 36))
        
        navigationItem.titleView = titleView
        
        // 3. 添加子控件
        // 1) 创建子控件
        let titleLabel = UILabel.init(title: "发微博", fontSize: 15, color: UIColor.lightGrayColor())
        let nameLabel = UILabel.init(title: UserAccountViewModel.shareUserAccount.account?.screen_name ?? "", fontSize: 13, color: UIColor.lightGrayColor())
        // 2) 添加到标题视图中
        titleView.addSubview(titleLabel)
        titleView.addSubview(nameLabel)
        // 3) 布局
        titleLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(titleView.snp_top)
            make.centerX.equalTo(titleView.snp_centerX)
        }
        nameLabel.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(titleView.snp_bottom)
            make.centerX.equalTo(titleView.snp_centerX)
        }
    }
    
    // MARK: 准备文本视图
    private func prepareForTextView() {
        
        // 1. 添加控件
        view.addSubview(textView)
        textView.addSubview(placeHolderLabel)
        
        // 2. 布局
        textView.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(self.snp_topLayoutGuideBottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.bottom.equalTo(toolbar.snp_top)
        }
        
        placeHolderLabel.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(textView.snp_top).offset(8)
            make.left.equalTo(textView.snp_left).offset(5)
        }
    }
    
    // MARK: 准备工具条
    private func prepareForToolbar() {
        // 1. 添加控件
        view.addSubview(toolbar)
        // 设置背景颜色
        toolbar.backgroundColor = UIColor(white: 0.8, alpha: 1.0)
        
        // 2. 自动布局
        toolbar.snp_makeConstraints { (make) -> Void in
            make.bottom.equalTo(view.snp_bottom)
            make.left.equalTo(view.snp_left)
            make.right.equalTo(view.snp_right)
            make.height.equalTo(44)
        }
        
        // 3. 添加按钮
        let itemSettings = [["imageName": "compose_toolbar_picture","actionName": "selectPicture"],
            ["imageName": "compose_mentionbutton_background"],
            ["imageName": "compose_trendbutton_background"],
            ["imageName": "compose_emoticonbutton_background", "actionName": "selectEmoticon"],
            ["imageName": "compose_addbutton_background"]]
        
        var items = [UIBarButtonItem]()
        
        for dict in itemSettings {
            items.append(UIBarButtonItem.init(imageName: dict["imageName"]!, target: self, actionName: dict["actionName"]))
            items.append(UIBarButtonItem.init(barButtonSystemItem: .FlexibleSpace, target: nil, action: nil))
        }
        items.removeLast()
        
        // 一旦复制，就相当于做了一次copy
        toolbar.items = items
    }
}